﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using mvcForum.Core;
using mvcForum.Core.Interfaces.Data;
using mvcForum.DataProvider.EntityFramework.Repositories;
using mvcForum.Core.Interfaces.DependencyManagement;

namespace mvcForum.DataProvider.EntityFramework {

	public class MigConf : DbMigrationsConfiguration<MembershipDbContext> {
		public MigConf() : base() {
			this.AutomaticMigrationsEnabled = true;
		}
	}

	public class DataProviderConfiguration : /*IDataProviderConfiguration*/ IDependencyBuilder {
		private readonly Boolean create;

		public DataProviderConfiguration() : this(true) { }

		public DataProviderConfiguration(Boolean createDatabase) {
			this.create = createDatabase;
		}

		public virtual void Configure(IDependencyContainer container) {
			if (create) {
				Database.SetInitializer<MembershipDbContext>(new CreateDatabaseIfNotExists<MembershipDbContext>());
			}
			else {
				Database.SetInitializer<MembershipDbContext>(new MigrateDatabaseToLatestVersion<MembershipDbContext, MigConf>());
			}

			container.RegisterPerRequest<IContext, Context>();
			container.RegisterPerRequest<DbContext, MembershipDbContext>(new Dictionary<String, Object> { { "nameOrConnectionString", ConfigurationManager.ConnectionStrings["mvcForum.DataProvider.MainDB"].ConnectionString } });
			//container.RegisterPerRequest<DbContext, ProfilerContext>(new Dictionary<String, Object> { { "nameOrConnectionString", ConfigurationManager.ConnectionStrings["mvcForum.DataProvider.MainDB"].ConnectionString } });

			container.RegisterGeneric(typeof(IRepository<>), typeof(Repository<>));

			// TODO: Do this in some other way!!
			new SpecificRepositoryConfiguration().Configure(container);
		}

		public virtual void ValidateRequirements(IList<ApplicationRequirement> feedback) {
			if (ConfigurationManager.ConnectionStrings["mvcForum.DataProvider.MainDB"] == null) {
				feedback.Add(new ApplicationRequirement {
					Feedback = @"No connection found for mvcForum, please insert this into the application's web.config file:

<configuration>
	<connectionStrings>
		<add name=""mvcForum.DataProvider.MainDB""
			connectionString=""Data Source=SQLSERVERNAMEorSQLSERVERNAME\INSTANCE;Initial Catalog=DATABASE;User ID=USERNAME;password=PASSWORD""
		/>
	</connectionStrings>
</configuration>

Remember to replace the values in the connection string with values that matches your set-up.
",
					Level = RequirementLevel.Fatal
				});
			}
			else {
				feedback.Add(new ApplicationRequirement { Feedback = "Connection string for MVC Forum located.", Level = RequirementLevel.Info });
			}
		}
	}
}